package com.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.springboot.common.ResponseCode;
import com.springboot.common.Result;
import com.springboot.service.IUsersService;
import com.springboot.entity.Users;
import com.springboot.mapper.UsersMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.utils.CustomStringUtils;
import com.springboot.utils.IntegerUtils;
import com.springboot.utils.JwtTokenUtils;
import com.springboot.vo.UserLoginVO;
import com.springboot.vo.UsersOpVO;
import com.springboot.vo.UsersVO;
import jakarta.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * 用户 服务实现类
 *
 * @author zjb
 * @since 2025-09-09 14:15
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {
    @Resource
    private UsersMapper usersMapper;

    /**
     * 用户登录
     *
     * @param userLoginVO 登录信息（手机号和密码）
     * @return 登录结果，包含用户信息和token
     */
    @Override
    public Result login(UserLoginVO userLoginVO) {
        String account = userLoginVO.getPhoneNumber();
        String password = userLoginVO.getPassword();
        if (!StringUtils.hasText(account) || !StringUtils.hasText(password)) {
            return Result.error("账号或密码不能为空");
        }
        Users users = usersMapper.login(account, password);
        if (users == null) {
            return Result.error("账号或密码错误");
        }
        if (Objects.equals(users.getStatus(), "0")) {
            return Result.error(ResponseCode.FORBIDDEN, "您的账号被禁用");
        }
        UsersVO usersVo = new UsersVO();
        BeanUtils.copyProperties(users, usersVo);
        String token = JwtTokenUtils.getToken(users.getUserId().toString(), users.getPassword());
        usersVo.setToken(token);
        return Result.success(usersVo, "登录成功");
    }

    /**
     * 用户注册
     *
     * @param users 用户注册信息
     * @return 注册结果
     */
    @Override
    public Result register(Users users) {
        if (!IntegerUtils.isNull(users.getUserId())) {
            return Result.error("用户不能指定id");
        }
        if (!StringUtils.hasText(users.getPhoneNumber())) {
            return Result.error("电话号码不能为空");
        }
        if (!StringUtils.hasText(users.getPassword())) {
            return Result.error("密码不能为空");
        }
        if (!StringUtils.hasText(users.getEmail())) {
            return Result.error("邮箱不能为空");
        }
        if (!StringUtils.hasText(users.getUserName())) {
            return Result.error("用户名不能为空");
        }
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getPhoneNumber, users.getPhoneNumber()).or()
                .eq(Users::getEmail, users.getEmail()).or()
                .eq(Users::getUserName, users.getUserName());
        List<Users> usersList = list(queryWrapper.select(Users::getUserName, Users::getEmail, Users::getPhoneNumber));
        if (!usersList.isEmpty()) {
            for (Users user : usersList) {
                if (Objects.equals(user.getUserName(), users.getUserName())) {
                    return Result.error("用户名已被注册");
                }
                if (Objects.equals(user.getEmail(), users.getEmail())) {
                    return Result.error("邮箱已被注册");
                }
                if (Objects.equals(user.getPhoneNumber(), users.getPhoneNumber())) {
                    return Result.error("电话号码已被注册");
                }
            }
        }
        users.setRole("user");
        if (this.save(users)) {
            return Result.success("注册成功");
        } else {
            return Result.error("注册失败");
        }

    }

    /**
     * 查询所有用户（支持分页和条件查询）
     *
     * @param pageNum  页码
     * @param pageSize 每页大小
     * @param gender   性别筛选条件
     * @param search   搜索关键字
     * @return 用户分页数据
     */
    @Override
    public Result searchUsersAll(Integer pageNum, Integer pageSize, String gender, String search) {
        // 创建查询条件
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(gender)) {
            queryWrapper.eq(Users::getGender, gender);
        }

        if (StringUtils.hasText(search)) {
            queryWrapper.like(Users::getUserName, search)
                    .or()
                    .like(Users::getPhoneNumber, search)
                    .or()
                    .like(Users::getEmail, search);
        }
        //分页查询
        IPage<Users> page = new Page<>(pageNum, pageSize);
        IPage<Users> usersIPage = this.page(page, queryWrapper);
        return Result.success(usersIPage, "查询成功");
    }

    /**
     * 更新用户信息
     *
     * @param userId 用户ID
     * @param users  用户信息
     * @return 更新结果
     */
    @Override
    public Result updateUserInfo(Integer userId,Users users) {
        if (IntegerUtils.isEmptyOrZero(userId)) {
            return Result.error("用户id不能为空或非法值");
        }
        // 权限验证
        Integer currentUserId = JwtTokenUtils.getCurrentUser().getUserId();
        if (!Objects.equals(userId, currentUserId)) {
            return Result.error(ResponseCode.FORBIDDEN, "不能修改他人信息");
        }
        users.setUserId(userId);
        if (CustomStringUtils.isEmpty(users.getUserName())) {
            return Result.error("用户名不能为非法值");
        }
        if (CustomStringUtils.isEmpty(users.getPhoneNumber())) {
            return Result.error("电话号码不能为非法值");
        }
        if (CustomStringUtils.isEmpty(users.getEmail())) {
            return Result.error("邮箱不能为非法值");
        }
        // 获取原始用户信息
        Users oldInfo = getById(users.getUserId());
        if (oldInfo == null) {
            return Result.error("用户不存在");
        }
        // 如果有字段变更，则检查是否与其他用户冲突
        boolean userNameChanged = users.getUserName() != null && !Objects.equals(users.getUserName(), oldInfo.getUserName());
        boolean emailChanged = users.getEmail() != null && !Objects.equals(users.getEmail(), oldInfo.getEmail());
        boolean phoneChanged = users.getPhoneNumber() != null && !Objects.equals(users.getPhoneNumber(), oldInfo.getPhoneNumber());


        if (userNameChanged || emailChanged || phoneChanged) {
            // 使用单次查询检查所有可能的冲突
            LambdaQueryWrapper<Users> conflictCheckQuery = new LambdaQueryWrapper<>();
            conflictCheckQuery.ne(Users::getUserId, currentUserId); // 排除当前用户

            // 添加所有变更字段的检查条件
            if (userNameChanged) {
                conflictCheckQuery.eq(Users::getUserName, users.getUserName()).or();
            }
            if (emailChanged) {
                conflictCheckQuery.eq(Users::getEmail, users.getEmail()).or();
            }
            if (phoneChanged) {
                conflictCheckQuery.eq(Users::getPhoneNumber, users.getPhoneNumber());
            }


            // 执行一次查询检查所有冲突
            List<Users> conflictingUsers = list(conflictCheckQuery.select(Users::getUserId, Users::getUserName,
                    Users::getEmail, Users::getPhoneNumber));

            // 分析冲突结果
            for (Users conflictingUser : conflictingUsers) {
                if (userNameChanged && Objects.equals(users.getUserName(), conflictingUser.getUserName())) {
                    return Result.error("用户名已被注册");
                }
                if (emailChanged && Objects.equals(users.getEmail(), conflictingUser.getEmail())) {
                    return Result.error("邮箱已被注册");
                }
                if (phoneChanged && Objects.equals(users.getPhoneNumber(), conflictingUser.getPhoneNumber())) {
                    return Result.error("电话号码已被注册");
                }
            }
        } else {
            // 如果所有字段都没改变
            return Result.error("未修改任何值");
        }

        // 更新用户信息
        boolean result = updateById(users);
        if (result) {
            Users updatedUser = getById(users.getUserId());
            UsersOpVO usersVo = new UsersOpVO();
            BeanUtils.copyProperties(updatedUser, usersVo);
            return Result.success(usersVo, "更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    /**
     * 修改用户状态
     *
     * @param id     用户id
     * @param status 状态(1-正常，0-禁用)
     * @return 结果
     */
    @Override
    public Result changeUserStatus(Integer id, Integer status) {
        if (!StringUtils.hasText(String.valueOf(id))) {
            return Result.error("用户id不能为空");
        }
        if (!StringUtils.hasText(String.valueOf(status))) {
            return Result.error("状态不能为空");
        }
        boolean result = update(new UpdateWrapper<Users>().eq("user_id", id).set("status", status));
        if (result) {
            return Result.success("修改成功");
        } else {
            return Result.error("修改失败");
        }
    }
}